﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 软构大作业
{
    public partial class Form2 : Form
    {
        private new AutoAdaptWindowsSize AutoSize;
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        public Form2()
        {
            InitializeComponent();
            checkBox2.CheckedChanged += checkBox2_CheckedChanged;
            checkBox1.CheckedChanged += checkBox1_CheckedChanged;
            // 设置窗体的KeyPreview属性为true，以便窗体可以接收键盘事件
            this.KeyPreview = true;
            // 为窗体添加KeyDown事件处理
            this.KeyDown += Form2_KeyDown;
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            //textBox4.Text = "";
            textBox5.Text = "";
            textBox6.Text = "";
            Global.Instance.form2login=null;
            Global.Instance.form1login.Show();
        }
        private void Form2_KeyDown(object sender, KeyEventArgs e)
        {
            // 检查是否按下Enter键
            if (e.KeyCode == Keys.Enter)
            {
                // 触发button1的点击事件
                button1.PerformClick();
                // 标记事件已处理，防止其他控件处理该事件
                e.Handled = true;
                e.SuppressKeyPress = true; // 防止发出"叮"的声音
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            // 用户名验证：6-20位字母、数字、下划线
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                MessageBox.Show("用户名不能为空！");
                return;
            }
            if (!Regex.IsMatch(textBox1.Text, @"^[a-zA-Z0-9_]{3,20}$"))
            {
                MessageBox.Show("用户名需3-20位字母、数字或下划线！");
                return;
            }

            // 密码验证：至少8位，包含字母和数字
            if (string.IsNullOrEmpty(textBox2.Text))
            {
                MessageBox.Show("密码不能为空！");
                return;
            }
            if (!Regex.IsMatch(textBox2.Text, @"^(?=.*[a-zA-Z])(?=.*\d).{5,}$"))
            {
                MessageBox.Show("密码需至少5位，且包含字母和数字！");
                return;
            }

            // 确认密码验证：与密码一致
            if (textBox3.Text != textBox2.Text)
            {
                MessageBox.Show("密码不一致！");
                return;
            }

            // 手机号验证：标准中国大陆手机号
            if (string.IsNullOrEmpty(textBox5.Text))
            {
                MessageBox.Show("手机号不能为空！");
                return;
            }
            if (!Regex.IsMatch(textBox5.Text, @"^1[3-9]\d{9}$"))
            {
                MessageBox.Show("手机号格式错误！");
                return;
            }

            // 学号/工号验证：6-12位字母数字
            if (string.IsNullOrEmpty(textBox6.Text))
            {
                MessageBox.Show("学号/工号不能为空！");
                return;
            }
            if (!Regex.IsMatch(textBox6.Text, @"^[a-zA-Z0-9]{6,15}$"))
            {
                MessageBox.Show("学号/工号需6-15位字母或数字！");
                return;
            }

            // 检查用户名是否已存在
            if (CheckUsernameExists(textBox1.Text))
            {
                MessageBox.Show("用户名已存在，请更换！");
                return;
            }

            // 插入新用户到数据库
            try
            {
                string sql = @"
            INSERT INTO library_db.users 
            (username, password, phone, student_id, permission, request) 
            VALUES 
            (@Username, @Password, @Phone, @StudentId, @Permission, @Request)";

                SqlParameter[] parameters = new SqlParameter[]
                {
            new SqlParameter("@Username", textBox1.Text.Trim()),
            new SqlParameter("@Password", textBox2.Text.Trim()), // 实际项目中应该加密存储
            new SqlParameter("@Phone", textBox5.Text.Trim()),
            new SqlParameter("@StudentId", textBox6.Text.Trim()),
            new SqlParameter("@Permission", true), // 新用户默认Permission=True
            new SqlParameter("@Request", "No") // 新用户默认Request="No"
                };

                int rowsAffected = Data.ExecuteNonQuery(sql, parameters);

                if (rowsAffected > 0)
                {
                    MessageBox.Show("注册成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // 清空输入框并返回登录界面
                    textBox1.Text = "";
                    textBox2.Text = "";
                    textBox3.Text = "";
                    textBox5.Text = "";
                    textBox6.Text = "";
                    Global.Instance.form2login.Hide();
                    Global.Instance.form1login.Show();
                }
                else
                {
                    MessageBox.Show("注册失败，请重试！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"注册时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            textBox2.UseSystemPasswordChar = !checkBox1.Checked;
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            textBox3.UseSystemPasswordChar = !checkBox2.Checked;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            //textBox4.Text = "";
            textBox5.Text = "";
            textBox6.Text = "";
            Global.Instance.form2login.Hide();
            Global.Instance.form1login.Show();
        }
        private bool CheckUsernameExists(string username)
        {
            try
            {
                string sql = "SELECT COUNT(*) FROM library_db.users WHERE username = @Username";
                DataTable dt = Data.ExecuteQuery(sql, new SqlParameter("@Username", username));

                if (dt != null && dt.Rows.Count > 0)
                {
                    int count = Convert.ToInt32(dt.Rows[0][0]);
                    return count > 0;
                }
                return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"数据库查询错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true; // 如果查询出错，默认认为用户名存在以防止重复
            }
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            AutoSize = new AutoAdaptWindowsSize(this);
            this.SizeChanged += new EventHandler(Form_SizeChanged);
        }

        private void Form_SizeChanged(object sender, EventArgs e)
        {//窗体大小改变事件
            if (AutoSize != null) // 一定加这个判断，电脑缩放布局不是100%的时候，会报错
            {
                AutoSize.FormSizeChanged();
            }
        }
    }
}
